import Foundation
import CoreLocation

// MARK: - 坐标测试工具

class CoordinateTestTool {
    static let shared = CoordinateTestTool()
    
    private init() {}
    
    // MARK: - 测试坐标
    
    func testCoordinate() {
        let latitude = 35.92277166666667
        let longitude = 139.48274166666667
        let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
        
        print("🧪 === 开始测试坐标 ===")
        print("📍 测试坐标: \(latitude), \(longitude)")
        print("📍 坐标对象: \(coordinate)")
        
        // 验证坐标有效性
        if CLLocationCoordinate2DIsValid(coordinate) {
            print("✅ 坐标有效")
        } else {
            print("❌ 坐标无效")
            return
        }
        
        // 测试苹果地理编码
        testAppleGeocoding(coordinate: coordinate)
        
        // 测试高德地图API
        testAMapGeocoding(coordinate: coordinate)
        
        // 测试腾讯地图API
        testTencentGeocoding(coordinate: coordinate)
        
        // 测试谷歌地图API
        testGoogleGeocoding(coordinate: coordinate)
        
        // 测试OpenStreetMap
        testOpenStreetMapGeocoding(coordinate: coordinate)
    }
    
    // MARK: - 苹果地理编码测试
    
    private func testAppleGeocoding(coordinate: CLLocationCoordinate2D) {
        print("\n🍎 === 测试苹果地理编码 ===")
        
        let geocoder = CLGeocoder()
        let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
        
        geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
            if let error = error {
                print("❌ 苹果地理编码失败: \(error.localizedDescription)")
                print("❌ 错误代码: \(error)")
                return
            }
            
            guard let placemarks = placemarks, !placemarks.isEmpty else {
                print("❌ 苹果地理编码未找到地址信息")
                return
            }
            
            let placemark = placemarks.first!
            print("✅ 苹果地理编码成功:")
            print("   - 国家: \(placemark.country ?? "未知")")
            print("   - 省份: \(placemark.administrativeArea ?? "未知")")
            print("   - 城市: \(placemark.locality ?? "未知")")
            print("   - 区县: \(placemark.subLocality ?? "未知")")
            print("   - 街道: \(placemark.thoroughfare ?? "未知")")
            print("   - 详细地址: \(placemark.subThoroughfare ?? "未知")")
            print("   - 邮政编码: \(placemark.postalCode ?? "未知")")
            print("   - ISO国家代码: \(placemark.isoCountryCode ?? "未知")")
        }
    }
    
    // MARK: - 高德地图API测试
    
    private func testAMapGeocoding(coordinate: CLLocationCoordinate2D) {
        print("\n🗺️ === 测试高德地图API ===")
        
        let apiKey = "your_amap_key_here" // 需要替换为实际的API密钥
        let urlString = "https://restapi.amap.com/v3/geocode/regeo?key=\(apiKey)&location=\(coordinate.longitude),\(coordinate.latitude)&output=json&extensions=all"
        
        guard let url = URL(string: urlString) else {
            print("❌ 无效URL")
            return
        }
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            if let error = error {
                print("❌ 网络请求失败: \(error.localizedDescription)")
                return
            }
            
            guard let data = data else {
                print("❌ 无响应数据")
                return
            }
            
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print("✅ 高德地图API响应:")
                print("   - 原始数据: \(json)")
                
                // 尝试解析JSON
                if let dict = json as? [String: Any],
                   let status = dict["status"] as? String {
                    print("   - 状态: \(status)")
                    
                    if let info = dict["info"] as? String {
                        print("   - 信息: \(info)")
                    }
                    
                    if let regeocode = dict["regeocode"] as? [String: Any] {
                        print("   - 地址信息: \(regeocode)")
                    }
                }
            } catch {
                print("❌ JSON解析失败: \(error)")
            }
        }.resume()
    }
    
    // MARK: - 腾讯地图API测试
    
    private func testTencentGeocoding(coordinate: CLLocationCoordinate2D) {
        print("\n🗺️ === 测试腾讯地图API ===")
        
        let apiKey = "your_tencent_key_here" // 需要替换为实际的API密钥
        let urlString = "https://apis.map.qq.com/ws/geocoder/v1/?location=\(coordinate.latitude),\(coordinate.longitude)&key=\(apiKey)&get_poi=1"
        
        guard let url = URL(string: urlString) else {
            print("❌ 无效URL")
            return
        }
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            if let error = error {
                print("❌ 网络请求失败: \(error.localizedDescription)")
                return
            }
            
            guard let data = data else {
                print("❌ 无响应数据")
                return
            }
            
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print("✅ 腾讯地图API响应:")
                print("   - 原始数据: \(json)")
            } catch {
                print("❌ JSON解析失败: \(error)")
            }
        }.resume()
    }
    
    // MARK: - 谷歌地图API测试
    
    private func testGoogleGeocoding(coordinate: CLLocationCoordinate2D) {
        print("\n🗺️ === 测试谷歌地图API ===")
        
        let apiKey = "your_google_key_here" // 需要替换为实际的API密钥
        let urlString = "https://maps.googleapis.com/maps/api/geocode/json?latlng=\(coordinate.latitude),\(coordinate.longitude)&key=\(apiKey)&language=zh-CN"
        
        guard let url = URL(string: urlString) else {
            print("❌ 无效URL")
            return
        }
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            if let error = error {
                print("❌ 网络请求失败: \(error.localizedDescription)")
                return
            }
            
            guard let data = data else {
                print("❌ 无响应数据")
                return
            }
            
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print("✅ 谷歌地图API响应:")
                print("   - 原始数据: \(json)")
            } catch {
                print("❌ JSON解析失败: \(error)")
            }
        }.resume()
    }
    
    // MARK: - OpenStreetMap测试
    
    private func testOpenStreetMapGeocoding(coordinate: CLLocationCoordinate2D) {
        print("\n🌍 === 测试OpenStreetMap ===")
        
        let urlString = "https://nominatim.openstreetmap.org/reverse?lat=\(coordinate.latitude)&lon=\(coordinate.longitude)&format=json&accept-language=zh-CN"
        
        guard let url = URL(string: urlString) else {
            print("❌ 无效URL")
            return
        }
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            if let error = error {
                print("❌ 网络请求失败: \(error.localizedDescription)")
                return
            }
            
            guard let data = data else {
                print("❌ 无响应数据")
                return
            }
            
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print("✅ OpenStreetMap响应:")
                print("   - 原始数据: \(json)")
            } catch {
                print("❌ JSON解析失败: \(error)")
            }
        }.resume()
    }
}

// MARK: - 运行测试

// 在需要的地方调用
// CoordinateTestTool.shared.testCoordinate() 